package com.flca.frw.zk.helper;

import org.zkoss.zk.ui.Desktop;
import org.zkoss.zk.ui.Execution;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.Page;
import org.zkoss.zk.ui.Session;
import org.zkoss.zul.Window;

public abstract class BaseSessionState {

	private static final String PAGENAME = "pagename";

	/**
	 * Stores the given object in the session context, it can be retrieved via
	 * restore(TheStoredObject.class)
	 * 
	 * @param aObject
	 */
	public static void store(Object aObject) {
		if (aObject != null) {
			getSession().setAttribute(aObject.getClass().getSimpleName(), aObject);
		}
	}

	/**
	 * Stores the given object in the session context, it can be retrieved via
	 * restore(TheStoredObject.class)
	 * 
	 * @param aObject
	 */
	public static void store(String aKey, Object aObject) {
		store(getSession(), aKey, aObject);
	}

	private static void store(Session aSession, Object aObject) {
		if (aObject != null) {
			aSession.setAttribute(aObject.getClass().getSimpleName(), aObject);
		}
	}

	public static void store(Session aSession, String aKey, Object aObject) {
		if (aObject != null) {
			aSession.setAttribute(aKey, aObject);
		}
	}

	public static Object retrieve(String aKey) {
		return retrieve(getSession(), aKey);
	}

	public static Object retrieve(Class<?> aClass) {
		return retrieve(getSession(), aClass);
	}

	public static Object retrieve(Window aWindow, Class<?> aClass) {
		Object result = aWindow.getDesktop().getSession().getAttribute(aClass.getSimpleName());
		return result;
	}

	public static Object retrieve(Session aSession, String aKey) {
		Object result = aSession.getAttribute(aKey);
		return result;
	}

	public static Object retrieve(Session aSession, Class<?> aClass) {
		Object result = aSession.getAttribute(aClass.getSimpleName());
		return result;
	}

	public static void storePageName(Window aWindow) {
		Page currPage = aWindow.getPage();
		String pagePath = currPage.getRequestPath();
		aWindow.getDesktop().getSession().setAttribute(PAGENAME, pagePath);
	}

	public static String getPageName() {
		return (String) getSession().getAttribute(PAGENAME);
	}

//	public static TestParameters getTestParams() {
//		TestParameters result = null;
//		try {
//			result = (TestParameters) retrieve(getSession(), TestParameters.class);
//			if (result == null) {
//				String xml = FileUtils.readResource(BaseSessionState.class, "/testparameters.xml");
//				XStream xs = new XStream();
//				result = (TestParameters) xs.fromXML(xml);
//				store(getSession(), result);
//			}
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//		return result;
//	}

	public static Session getSession() {
		Execution execution = Executions.getCurrent();
		if (execution != null) {
			Desktop desktop = execution.getDesktop();
			if (desktop != null) {
				return desktop.getSession();
			}
		}

		return null;
	}

}
